package space.panker916.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;


@Component
public class MailClient {
    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}" + "(panker)")  // 邮件的发件人
    private String from;

    /**
     * 封装了发送邮件的工具类
     *
     * @param to      收件人的邮箱
     * @param subject 邮件的标题
     * @param text    邮件的正文内容（其实使用 thymeleaf TemplateEngine 生成的 HTML 模板）
     * @throws MessagingException
     */
    public void sendMail(String to, String subject, String text) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text, true);         // 支持 HTML 语法
        mailSender.send(message);
    }

}
